//
//  UserViewController.m
//  test
//
//  Created by 朱圳 on 2017/12/18.
//  Copyright © 2017年 朱圳. All rights reserved.
//

#import "UserViewController.h"
#import "UserInfoCell.h"
#import "StuPersonEduViewController.h"
#import "SafeViewController.h"
#import "StuUserViewController.h"
#import "OrderViewController.h"//我的约课
#import "ClockDaysVC.h"//打卡管理
#import "ClassManageVC.h"//上课管理
#import "PersonHeadView.h"//个人中心头
#import <AVFoundation/AVFoundation.h>
#define PersonHeadViewID @"PersonHeadView"

@interface UserViewController()<UITableViewDelegate,UITableViewDataSource,ChangeImgDelegate,UIActionSheetDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *listarray;
@property (nonatomic, strong) UIImagePickerController *picker;
@property (strong, nonatomic)UIImage *img;
@end

@implementation UserViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"个人信息";
    NSString *path = [[NSBundle mainBundle] pathForResource:@"User.plist" ofType:nil];
    self.listarray =[NSMutableArray arrayWithContentsOfFile:path];
    
    [self.view addSubview:self.tableView];
}

-(void)changeImage:(UITapGestureRecognizer *)sender{
    __block typeof (self) weak_self = self;
    
    _picker = [[UIImagePickerController alloc] init];
    _picker.delegate = self;
    _picker.allowsEditing = YES;
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"请选择图片"
                                                                             message:@""
                                                                      preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * action) {}];
    UIAlertAction* fromPhotoAction = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault                                                                 handler:^(UIAlertAction * action) {
        weak_self.picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [weak_self presentViewController:weak_self.picker animated:YES completion:nil];
        NSLog(@"从相册选择");
    }];
    UIAlertAction* fromCameraAction = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault                                                             handler:^(UIAlertAction * action) {
        NSLog(@"相机");
        
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
        if(! [UIImagePickerController isSourceTypeAvailable:sourceType]){
            NSString *tips = @"相机不可用";
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"无法使用相机" message:tips preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                NSLog(@"取消");
            }];
            UIAlertAction *otherAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                NSLog(@"确定");
            }];
            [alertController addAction:cancelAction];
            [alertController addAction:otherAction];
            [self presentViewController:alertController animated:YES completion:nil];
            return;
        }
        _picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:_picker animated:YES completion:nil];
        if (![self getCameraRecordPermisson]) {
            NSString *tips = @"请在iPhone的“设置-隐私-相机”中允许访问相机";
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"无法使用相机" message:tips preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                NSLog(@"取消");
            }];
            UIAlertAction *otherAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                NSLog(@"确定");
            }];
            [alertController addAction:cancelAction];
            [alertController addAction:otherAction];
            [self presentViewController:alertController animated:YES completion:nil];
            
        }
        
    }];
    [alertController addAction:cancelAction];
    [alertController addAction:fromCameraAction];
    [alertController addAction:fromPhotoAction];
    [self presentViewController:alertController animated:YES completion:nil];
  
}
#pragma -mark -----------------------------tableview datasource and delegate---------------------------------
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return   1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return   self.listarray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 49;
}
#pragma mark  ---UICollectionView---
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 2;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (section ==0) {
        return 1;
    }else{
        return self.listarray.count;
        
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 1.创建cell
    static NSString *ID = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
        cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.imageView.size = CGSizeMake(25, 25);
    }
    
    cell.textLabel.text=self.listarray[indexPath.row][@"name"];
    cell.imageView.image=[UIImage imageNamed:self.listarray[indexPath.row][@"img"]];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.row == 0) {
        StuUserViewController *vc = [[StuUserViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }
    if (indexPath.row == 1) {
        OrderViewController *vc = [[OrderViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }
    if (indexPath.row == 2) {
        ClassManageVC *vc = [[ClassManageVC alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }
//    if (indexPath.row == 3) {
//        StudyChartsViewController *vc = [[StudyChartsViewController alloc]init];
//        vc.view.backgroundColor = [UIColor whiteColor];
//        [self.navigationController pushViewController:vc animated:YES];
//    }
    if (indexPath.row == 3) {
        StuPersonEduViewController *vc = [[StuPersonEduViewController alloc]init];
        vc.titles = @"1";
        [self.navigationController pushViewController:vc animated:YES];
    }
    if (indexPath.row == 4) {
        StuPersonEduViewController *vc = [[StuPersonEduViewController alloc]init];
        vc.titles = @"2";
        [self.navigationController pushViewController:vc animated:YES];
    }
    if (indexPath.row == 5) {
        ClockDaysVC *vc = [[ClockDaysVC alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }if (indexPath.row == 6) {
        SafeViewController * vc = [[SafeViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 180;
}

#pragma -mark 头部的内容
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    PersonHeadView *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:PersonHeadViewID];
    header.GraduteName.text=[[NSUserDefaults standardUserDefaults] objectForKey:@"name"];
    header.delegate = self;
    if (self.img == nil) {
        NSString *imgUrl = [NSString stringWithFormat:@"%@%@",ImageBaseURL,[[NSUserDefaults standardUserDefaults] objectForKey:@"sImg"]];
        [header.txImg sd_setImageWithURL:[NSURL URLWithString:imgUrl] placeholderImage:[UIImage imageNamed:@"头像"]];
    }else{
        header.txImg.image = self.img;
    }

    return header;
}

#pragma mark  ---懒加载---
-(UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)style:UITableViewStyleGrouped];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerNib:[UINib nibWithNibName:@"PersonHeadView" bundle:nil] forHeaderFooterViewReuseIdentifier:PersonHeadViewID];
    }
    return _tableView;
}

#pragma mark UIImagePickerControllerDelegate
//选择图或者拍照后的回调
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIImage *orignalImage = [info objectForKey:UIImagePickerControllerOriginalImage];//原图
    UIImage *editedImage = [info objectForKey:UIImagePickerControllerEditedImage];//编辑后的图片
    self.img = editedImage;
     [self.tableView reloadData];
    // 拍照后保存原图片到相册中
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera && orignalImage) {
        UIImageWriteToSavedPhotosAlbum(orignalImage, self, nil, NULL);
    }
    //上传照片
    [picker dismissViewControllerAnimated:YES completion:^{
                if (editedImage) {
                    [self doUploadPhoto:editedImage];
                }
    }];
}

-(void)doUploadPhoto:(UIImage *)img{
    
    NSDictionary *dict=@{
                        @"sid" : Sid,
                        @"spass" : Spassword,
                        };
     NSData *fileData = UIImageJPEGRepresentation(img, 1.0);
    [[AFNetworkTool shareManager]upLoadSinglePictureWithUrl:Stu_Headimg parameters:dict fileData:fileData progerss:^(NSProgress * _Nullable progress) {
    } success:^(id  _Nullable json) {
            NSUserDefaults *userDefaults =[NSUserDefaults standardUserDefaults];
            [userDefaults removeObjectForKey:@"sImg"];
            [userDefaults setObject:json[@"pic"] forKey:@"sImg"];
           [self.tableView reloadData];
    } failure:^(NSError * _Nullable error) {

    }];
}
//获得设备是否有访问相机权限
-(BOOL)getCameraRecordPermisson
{
    NSString * mediaType = AVMediaTypeVideo;
    AVAuthorizationStatus  authorizationStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
    if (authorizationStatus == AVAuthorizationStatusRestricted|| authorizationStatus == AVAuthorizationStatusDenied)
    {
        return NO;
    }
    return YES;
}
@end
